package com.exsun.ex1077.ui.activity.bounds

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.drake.brv.utils.*
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityBoundsListBinding
import com.exsun.ex1077.databinding.ItemBoundsBinding
import com.exsun.ex1077.model.MenuPermission
import com.exsun.ex1077.network.entity.Bounds
import com.exsun.ex1077.ui.view.SmartEditText
import com.lxj.xpopup.core.BasePopupView
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.SimpleXPopupCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.afterTextChange
import com.zhangping.fastjetpack.extend.view.disableItemChangeAnimation
import com.zhangping.fastjetpack.extend.view.textString
import com.zhangping.fastjetpack.ui.popup.InputPopup
import kotlinx.android.synthetic.main.activity_bounds_list.*

/**
 * 描述：围栏列表
 * 作者：ZhangPing
 * 创建时间：2023/3/27 10:25
 */
class BoundsListActivity: BaseActivity<BoundsListViewModel, ActivityBoundsListBinding>() {

    override fun title() = "电子围栏"
    override fun actionIcon() = if (menuPermission.add) R.drawable.action_add_44 else 0
    override fun barBgColor() = R.color.transparent

    private lateinit var menuPermission: MenuPermission

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        menuPermission = intent.getSerializableExtra("menuPermission") as MenuPermission
        super.initView(savedInstanceState)
        listView.disableItemChangeAnimation()
        listView.linear().divider {
            setDivider(1, true)
            setColor(R.color.divider.toColorRes())
        }.setup {
            addType<Bounds> { R.layout.item_bounds }
            onBind {
                val binding = getBinding<ItemBoundsBinding>()
                binding.rename.visible(menuPermission.rename)
                binding.edit.visible(menuPermission.edit)
                binding.delete.visible(menuPermission.remove)
            }
            onClick(R.id.rootView, R.id.rename, R.id.edit, R.id.delete){
                val model = getModel<Bounds>()
                when(it){
                    R.id.rootView -> {
                        toActivityForResult<BoundsDrawActivity>(Bundle().apply {
                            putInt("pageType", Constant.PAGE_TYPE_BOUNDS_PREVIEW)
                            putSerializable("model", model)
                        }){
                            if (it.resultCode != RESULT_OK) return@toActivityForResult
                            checkReturnResult(it.data!!)
                        }
                    }
                    R.id.rename -> {
                        showInput("围栏重命名", model.name, "请输入", builder = {
                            it.setPopupCallback(object : SimpleXPopupCallback() {
                                override fun onCreated(popupView: BasePopupView) {
                                    (popupView as InputPopup).getEditText()?.filters = arrayOf(SmartEditText.spaceFilter)
                                }
                            })
                        }, cancel = {
                            listView.closeMenus()
                        }){ popupView, content ->
                            listView.closeMenus()
                            mViewModel.boundsRename(model.id, content).observe(this@BoundsListActivity){
                                popupView.dismiss()
                                model.name = content
                                notifyItemChanged(modelPosition)
                            }
                        }
                    }
                    R.id.edit -> {
                        toActivityForResult<BoundsDrawActivity>(Bundle().apply {
                            putInt("pageType", Constant.PAGE_TYPE_BOUNDS_UPDATE)
                            putSerializable("model", model)
                        }){
                            if (it.resultCode != RESULT_OK) return@toActivityForResult
                            checkReturnResult(it.data!!)
                        }
                        postDelayed(1000){
                            listView.closeMenus()
                        }
                    }
                    R.id.delete -> {
                        showConfirm("确定删除”${model.name}“？", "", {
                            listView.closeMenus()
                        }){
                            mViewModel.boundsDelete(model.id).observe(this@BoundsListActivity){
                                mutable.removeAt(modelPosition)
                                notifyItemRemoved(modelPosition)
                            }
                        }
                    }
                }
            }
        }
        refreshLayout.onRefresh {
            mViewModel.loadData(1, searchEdit.textString())
        }.refresh()
        refreshLayout.onLoadMore {
            mViewModel.loadData(index, searchEdit.textString())
        }
        searchEdit.afterTextChange {
            refreshLayout.queueRefresh(false)
        }
    }

    override fun onActionClick(view: View) {
        toActivityForResult<BoundsDrawActivity>(Bundle().apply {
            putInt("pageType", Constant.PAGE_TYPE_BOUNDS_ADD)
        }){
            if (it.resultCode != RESULT_OK) return@toActivityForResult
            checkReturnResult(it.data!!)
        }
    }

    /**
     * 检查返回时的操作结果
     */
    private fun checkReturnResult(intent: Intent){
        val needDeleteId = intent.getStringExtra("needDeleteId")
        val needUpdateId = intent.getStringExtra("needUpdateId")
        val needRefresh = intent.getBooleanExtra("needRefresh", false)
        if (needDeleteId != null){
            val position = (listView.mutable as List<Bounds>).indexOfFirst { it.id == needDeleteId }
            if (position > -1){
                mViewModel.boundsDelete(needDeleteId).observe(this){
                    listView.mutable.removeAt(position)
                    listView.adapter!!.notifyItemRemoved(position)
                }
            }
        }else if (needUpdateId != null){
            val position = (listView.mutable as List<Bounds>).indexOfFirst { it.id == needUpdateId }
            if (position > -1){
                mViewModel.boundsQuery(needUpdateId).observe(this){
                    listView.mutable.set(position, it)
                    listView.adapter!!.notifyItemChanged(position)
                }
            }
        }else if (needRefresh){
            refreshLayout.refresh()
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.apply {
            dataLiveData.observe(this@BoundsListActivity){
                parseState(it, {
                    val list = it.rows ?: emptyList()
                    refreshLayout.queueAddData(list){ mViewModel.pageSize == list.size }
                },{
                    refreshLayout.queueRefreshException()
                })
            }
        }
    }

}